<?php
namespace Home\Controller;

use \Utuo\ForegroundController;
use My\Model\ProductOrderModel;

class ShopController extends ForegroundController {
	
	// 查询订单状态
	private $types = array(
			1 => "未付款订单",
			2 => "已付款订单",
			4 => "货到付款订单",
			3 => "交易成功订单",
			0 => "其它订单"
	);
	
	// 价格搜索区间
	private $prices = array(
			'1-49' => array( name => '1-49', value => '1-49'),
			'50-59' => array( name => '50-59', value => '50-59',),
	        '60-99' => array( name => '60-99', value => '60-99',),
			'100-199' => array( name =>'100-199', value => '100-199',),
			'200-299' => array( name =>'200-299', value => '200-299',),
			'300-399' => array( name =>'300-399', value => '300-399',),
			'400-599' =>  array( name =>'400-599', value => '400-599',),
			'600-799' => array( name =>'600-799', value => '600-799',),
			'800-' =>  array( name => '800以上', value => '800-',),
	);
	
	// 初始化
	public function _init() {
		layout('shop');
		$this->setModelName('PartnerProduct');
		$this->setModelControllerName();
	}
	
	// 首页
	public function indexAction() {
		$this->setPageTitle($this->config['name']);
		$this->display();
	}
	
	// 扩展信息
	public function configAction() {
		$id = I('id', 0, 'intval');
		$config = M('ProductConfig')->where("pid=%d AND id=%d", $this->pid, $id)->find();
		$this->assign('config', $config);
		$this->display();
	}
	
	// 商品栏目单页
    public function pageAction() {
    	$category = $this->getCategory();
    	$this->doDisplay( $category, 'page');
    }
    
	// 商品栏目列表
	public function cateAction() {
		$this->getCategory();
		$this->display();
	}
	
	// 商品列表
	public function listAction() {
		$this->getCategory();
		$result = $this->search();
		$result['baseCate'] = $this->catId;
		$this->assign("searchList", $result);
		$this->assign('searchListJSON', json_encode($result));
		$this->assign("baseCate", $result['baseCate'] ); // 设置了基础栏目
		$this->display();
	}
	
	
	// 商品详情页
	public function showAction() {
		$id = I('id', 0, 'intval');
		$map['pdt.pid'] = $this->pid;
		$map['pdt.status'] = 1;
		$map['pdt.is_deleted'] = 0;
		$map['pdt.id'] = $id;
		$dProductGoods = D("My/ProductGoods", "Model");
		$productGoods = M('ProductGoods pdt')->where($map)->join("__PRODUCT_GOODS_CONFIG__ cfg on cfg.id=pdt.id", 'LEFT')->find();
		$productGoods['attributes'] = $dProductGoods->getAttributesInfo($productGoods['attribute_values'], $id); // 获得属性信息
		$productGoods['shipping_cfg'] = $dProductGoods->getShippingWay($productGoods); // 获得送费标准
		$productGoods['pic'] = getImageUrl($productGoods['pic'], "show");
		$this->setPageTitle( $productGoods['name'], $this->config['name']);
		$this->assign('productGoods', $productGoods);
		$this->display();
	}
	
	
	/**
	 * 个人中心
	 */
	public function myAction() {
		$this->checkLogin();
		$this->getOrderNav();
		$this->setPageTitle('用户中心');
		$this->display();
	}
	

	/**
	 * 信息修改
	 */
	public function infoModifyAction() {
		$user = M("User")->find($this->uid);
		$this->assign("user", $user);
		$this->display();
	}
	
	// 搜索
	public function searchAction() {
		/*基础栏目限制*/
		$category = $this->getCategory();
		$baseCate = I('baseCate', 0, 'intval') and $baseCate = M('ProductCategory')->where('id=%d', $baseCate)->find();
		if( $baseCate and in_array("$this->catId", explode(',', $baseCate['path']))) { // 小于等于基础栏目
			$this->setCategory( $baseCate );
		}
		$this->ajaxReturn($this->search());
	}
	
	// 商品搜索
	private function search() {
		$category = $this->getCategory();
		$p = I("p", 1, "intval");
		$catId = $this->catId;
		$brandId = I('brands', 0, 'intval');
		$effId = I('efficiency', 0, 'intval');
		$keywords = I('keywords', '');
		$isLow = I('is_low', -1, 'intval');
		$price = I('prices', 0);
		$pageSize = $this->getPageSize();
		$page = $this->getPage();
		$condition = array( 'a.pid' => $this->pid, 'a.is_deleted' => 0, 'a.status' => 1 );
		$prices = $this->prices;
		if ( $price ) {
			list($min, $max) = explode('-', $price);
			$min*=1; $max*=1;
			if ( $min == $max ) {
				if ( $min != 0 ) {
					$condition['price'] = array('eq', $min);
				}
			} elseif ( !$max and $min ) {
				$condition['price'] = array('egt', $min);
			} elseif( !$min and $max ) {
				$condition['price'] = array('elt', $max);
			} else {
				$condition['price'] = array(array('gt', $min), array('lt', $max), 'and') ;
			}
		}
		if ( $keywords ) {
			$condition['a.name'] = array('like', "%$keywords%");
			$this->setPageTitle( $keywords );
		}
		if( $catId ) {
			$condition['b.path'] = array("exp", " is not null and find_in_set($catId, b.path) ");
			$this->setPageTitle( $category['name'] );
		}
		if ( $brandId ) {
			$condition['a.brand'] = array("exp", " is not null and find_in_set($brandId, a.brand) ");
			$productBrand = M("PartnerBrand a")->join("__PRODUCT_BRAND__ b on a.brand=b.id", "LEFT")->where("a.id=%d", $brandId)->field('a.id,case when a.name is not null then a.name when a.name is null then b.name end as name,a.brand')->find();
			$this->setPageTitle( $productBrand['name'] );
		}
		if ( $effId ) {
			$condition['a.efficiency'] = array("exp", " is not null and find_in_set($effId, a.efficiency) ");
			$productEfficiency = M("ProductEfficiency")->where("id=%d", $effId)->find();
			$this->setPageTitle( $productEfficiency['name'] );
		}
		if ( $isLow != -1 ) {
			$condition['a.is_low'] = ($isLow >=1 ? 1 : 0);
			$this->setPageTitle( '聚惠商品' );
		}		
		
		$m = M("ProductGoods a")->JOIN("__PRODUCT_CATEGORY__ b on a.cat_id=b.id", "LEFT")->where($condition);
		$n = clone $m;
		$list = $m->page($page)->limit($pageSize)->field('a.*')->select(); // ROUND(a.price/a.price_high*10, 1) as discount
		foreach ( $list as $k => &$v) {
			$v['discount'] = number_format(($v['is_low']?$v['price_low']:$v['price'])/$v['price_high']*10, 1);
		}
		$group = $n->field("GROUP_CONCAT(SUBSTRING_INDEX(SUBSTRING_INDEX(concat(b.path,',-'), ',', find_in_set($catId, concat(b.path,',-')) + 1), ',', -1)) as id, 
							GROUP_CONCAT(a.brand) as brands, GROUP_CONCAT(a.efficiency) as efficiency, count(*) as count")->find();
		
		if( !empty($group['id']) ) {
			$group['id'] = M("ProductCategory")->where(array('id' => array('in', $group['id'])))->field("id as value,name")->select();
			if ( $group['id'] ) {
				// 有子级
			} else { // 无子级
				$group['id'] = array();
			}
		} else {
			$group['id'] = array();
		}
		$catId and array_unshift($group['id'], array('value' => $category['id'], 'name' => $category['name'], 'selected' => 1 )); // 在查出的子级列表第一项加入当前选择的栏目
		$group['id'] = array_merge( array(array( 'value' => $category['pid']*1, 'name' => '全部分类', 'selected' => $catId==0 ? 1 : 0 ) ), $group['id'] );
		$menuSelected['id'] = $catId;
		
		if( !empty($group['brands']) ) {
			$group['brands'] = M("PartnerBrand a")->join("__PRODUCT_BRAND__ b on a.brand=b.id", "LEFT")->where(array('a.id' => array('in', $group['brands'])))->field('a.id as value,case when a.name is not null then a.name when a.name is null then b.name end as name')->select();
			$group['brands'] or $group['brands'] =  array();
		} else {
			$group['brands'] =  array();
			$productBrand and $group['brands'][] = array('value' => $productBrand['id'], 'name' => $productBrand['name'], 'selected' => 1 );
		}
		$group['brands'] = array_merge(array(array('value' => 0, 'name' => '全部品牌')), $group['brands']);
		foreach ( $group['brands'] as &$v) {
			if ( $v['value'] == $brandId ) {
				$v['selected'] = 1;
				break;
			}
		}
		$menuSelected['brands'] = $brandId;
		
		if( !empty($group['efficiency']) ) {
			$group['efficiency'] = M("ProductEfficiency")->where(array('id' => array('in', $group['efficiency'])))->field("id as value,name")->select();
		} else {
			$group['efficiency'] = array();
			$productEfficiency and $group['efficiency'][] = array('value' => $productEfficiency['id'], 'name' => $productEfficiency['name'], 'selected' => 1 );
		}
		$group['efficiency'] = array_merge(array(array('value' => 0, 'name' => '全部功效')), $group['efficiency']);
		foreach ( $group['efficiency'] as &$v) {
			if ( $v['value'] == $effId ) {
				$v['selected'] = 1;
				break;
			}
		}
		$menuSelected['efficiency'] = $effId;
		
		if( $price and !array_key_exists($price, $prices) ) { // 自定义搜索价格
			$prices = array_merge(array( 0 => array( 'name' => $price, 'value' => 0, 'selected' => 1)), $prices);
		}
		$prices = array_merge(array( 0 => array( 'name' => '全部价格', 'value' => 0)), $prices);
		if( array_key_exists($price, $prices) ) {
			$prices[$price]['selected'] = 1;
		}
		$menuSelected['prices'] = $price;
		
		$group['prices'] = $prices;
		$rowCount = $group['count'];
		unset( $group['count'] );
		
		$menuSelected['keywords'] = $keywords;
		
		foreach ($list as &$v)
			$v['url'] = U('Shop/show', array('pid'=>$this->pid, 'sid'=>$this->cid, 'id' => $v['id']));
		
		return array(
			'totalRows' => $rowCount,
			'totalPages' => ceil($rowCount / $pageSize),
			'page' => $page,
			'data' => $list,
			'menu' => $group,
			'menuSelected' => $menuSelected,
		);
	}
	
	/**
	 * 获得主题配置
	 * @param unknown $tid
	 * @return mixed
	 */
	protected function getThemeConfig( $tid ) {
		$themeConfig = M("ThemeConfig")->where("pid=%d and theme=%d", $this->pid, $tid)->getField("config");
		$themeConfig = unserialize($themeConfig);
		return $themeConfig;
	}
	
	// 订单导航
	private function getOrderNav() {
		$types = array();
		foreach (ProductOrderModel::$TYPES as $type => $v) {
			$condition = array(
					"uid" => $this->uid,
					"cid" => $this->sid
			);
			if ($type == 1) { // 未付款
				$condition['order_status'] = ProductOrderModel::ORDER_STATUS_PAY;
			} else if ($type == 2) { // 待签收(已付款,货到付款)
				$condition['order_status'] = array(
						"in",
						array(
								ProductOrderModel::ORDER_STATUS_SHIPPING,
								ProductOrderModel::ORDER_STATUS_SIGN
						)
				);
			} else if ($type == 3) { // 交易成功
				$condition['order_status'] = ProductOrderModel::ORDER_STATUS_COMPLETED;
			} else { // 其它
				$condition['order_status'] = array(
						"not in",
						array(
								ProductOrderModel::ORDER_STATUS_PAY,
								ProductOrderModel::ORDER_STATUS_SHIPPING,
								ProductOrderModel::ORDER_STATUS_SIGN,
								ProductOrderModel::ORDER_STATUS_COMPLETED
						)
				);
			}
			$count = M("ProductOrder")->where($condition)->count();
			$types[$type] = $v . "($count)";
		}
		$this->assign("types", $types);
	}
	
	// 更换栏目
	private function setCategory( $category ) {
		$this->catId = $category['id'];
		$this->category = $category;
		$this->getCategory();
	}
	
	// 获取目录
	private function getCategory() {
		if ( !$this->category ) {
			$id = I('id', 0, 'intval');
			$map['id'] = $id;
			$map['partner'] = $this->pid;
			$map['status'] = 1;
			$map['is_deleted'] = 0;
			$this->category = M('ProductCategory')->where($map)->find() or $this->catId = 0;
		}
		$this->setPageTitle($this->category['name'], $this->config['name']);
		$this->catId = $this->category['id']*1;
		$this->assign('category', $this->category);
		$this->assign('cat_id', $this->catId );
		return $this->category;
	}
	
	// 按设置的模板显示
	private function doDisplay( $category, $tplType, $rootPath ) {
		$siteThemeTpl = D("ThemeTpl", "Logic");
		$tpl = $siteThemeTpl->getCategoryTpl( unserialize($category['tpl_config']), $tplType );
		$this->display($tpl ? $rootPath.$tpl : $rootPath.ACTION_NAME);
	}
}